package cn.tedu.mall.seckill.controller;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.JsonResult;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import cn.tedu.mall.pojo.seckill.vo.SeckillCommitVO;
import cn.tedu.mall.seckill.exception.SeckillBlockHandler;
import cn.tedu.mall.seckill.exception.SeckillFallBack;
import cn.tedu.mall.seckill.service.ISeckillService;
import cn.tedu.mall.seckill.utils.SeckillCacheUtils;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author BJ
 * @date 2022/11/11 19:13
 */
@Controller
@RequestMapping("/seckill")
@Api(tags = "秒杀订单模块")
public class SeckillController {
    @Autowired
    private ISeckillService seckillService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/{randCode}")
    @ApiOperation("通过随机码验证用户是否秒杀成功")
    @PreAuthorize("hasRole('user')")
    @ApiImplicitParam(value = "randCode",name = "随机码",required = true)
    @SentinelResource(value = "seclill",
    blockHandlerClass = SeckillBlockHandler.class,blockHandler = "blockHandler",
    fallbackClass = SeckillFallBack.class,fallback = "fallBack")
    public JsonResult<SeckillCommitVO> getSeckillCommit(@PathVariable String randCode ,
                                                        @Validated SeckillOrderAddDTO seckillOrderAddDTO){
        String randCodeKey = SeckillCacheUtils.getRandCodeKey(seckillOrderAddDTO.getSpuId());

        if (redisTemplate.hasKey(randCodeKey)){
            if (!randCodeKey.equals(randCode)){
                throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST,"当前商品不存在！");
            }
            SeckillCommitVO seckillCommitVO = seckillService.commitSeckill(seckillOrderAddDTO);
            return JsonResult.ok(seckillCommitVO);

        }else {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"没有找到指定商品！");
        }
    }
}
